package ee.ut.maxorato_macobo.oop.mud.network;

import org.jboss.netty.channel.Channel;

import ee.ut.maxorato_macobo.oop.mud.game.GameUtils;
import ee.ut.maxorato_macobo.oop.mud.game.PlayerCharacter;
import ee.ut.maxorato_macobo.oop.mud.game.PlayerPool;

public class NetSession {
	private final Channel channel;
	private PlayerCharacter player;
	private String playerName;
	private int status;
	
	public NetSession(Channel newChannel) {
		channel = newChannel;
		player = null;
		status = 0;
	}
	
	public void sessionOpened() {
		System.out.println("Client ID " + channel.getId() + " connected.");
		
		sendOutput("Enter your name: ");
	}
	
	public void sessionClosed() {
		if(player != null) {
			PlayerPool.removePlayer(player);
		}
		
		System.out.println("Client ID " + channel.getId() + " disconnected.");
	}
	
	public void inputHandler(String text) {
		System.out.println("Client ID " + channel.getId() + " sent message: " + text);
		
		if(status == 0) {
			if(PlayerPool.isValidName(text)) {
				if(PlayerPool.existsGlobalPlayer(text)) {
					sendOutput("Existing player, enter password: ");
					status = 1;
				}
				else {
					sendOutput("New player, enter password: ");
					status = 2;
				}
				
				playerName = text;
			}
			else {
				sendOutput("Invalid name, try again: ");
			}
		}
		else if(status == 1) {
			if(PlayerPool.getGlobalPlayerHash(playerName) != GameUtils.shaValue(text)) {
				sendOutput("Wrong password, try again: ");
			}
			else {
				status = 3;
				
				player = PlayerPool.createPlayer(this, channel.getId().toString());
			}
		}
		else if(status == 2) {
			PlayerPool.saveGlobalPlayerHash(playerName, GameUtils.shaValue(text));
			
			sendOutput("Player created.\r\n");
			status = 3;
			
			player = PlayerPool.createPlayer(this, channel.getId().toString());
		}
		else if(status == 3) {
			player.inputText(text);
		}
	}
	
	public void sendOutput(String text) {
		channel.write(text);
	}
	
	public int getSessionId() {
		return channel.getId();
	}

	public void terminateSession() {
		channel.close();
	}
}
